﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace DenisVuyka.Controls.PropertyGrid.Data
{
  // Useful resources

  // C# - Sorting a Custom Collection
  // http://gibbons.co.za/archive/2005/02/09/255.aspx

  // Sorting an ObservableCollection<T> 
  // (http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/5909dbcc-9a9f-4260-bc36-de4aa9bbd383/)

  // How can I add my own sorting logic?
  // (http://www.beacosta.com/blog/?p=24)

  public class ObservableList<T> : ObservableCollection<T>
  {
    private List<T> InnerList
    {
      get { return (List<T>)base.Items; }
    }

    public ObservableList() : base() { }
    public ObservableList(IEnumerable<T> collection) : base(collection) { }
    public ObservableList(List<T> list) : base(list) { }

    public int BinarySearch(T item)
    {     
      return InnerList.BinarySearch(item);
    }

    public int BinarySearch(T item, IComparer<T> comparer)
    {
      return InnerList.BinarySearch(item, comparer);
    }

    public int BinarySearch(int index, int count, T item, IComparer<T> comparer)
    {
      return InnerList.BinarySearch(index, count, item, comparer);
    }

    public void Sort(Comparison<T> comparison)
    {
      InnerList.Sort(comparison);
      OnItemsChanged();
    }

    public void Sort(IComparer<T> comparer)
    {
      InnerList.Sort(comparer);
      OnItemsChanged();
    }

    public void Sort(int index, int count, IComparer<T> comparer)
    {
      InnerList.Sort(index, count, comparer);
      OnItemsChanged();
    }

    private void OnItemsChanged()
    {
      base.OnPropertyChanged(new PropertyChangedEventArgs("Item[]"));
      base.OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null, -1));
    }
  }
}
